<?php
/**
 * @description 菜单管理
 * @Author: eecjimmy
 * @CreateTime: 14-7-31 下午2:18
 */

namespace Addons\Weixin\Controller;


use Admin\Controller\AdminController;

define('WEIXIN_INCLUDE_PATH', ONETHINK_ADDON_PATH . 'Weixin/Include');

class MenuController extends AdminController
{
    protected $model;

    protected $cfg;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = M('weixin_menu')->order('sort desc');
        $addons = _get_addons('Weixin');
        $this->cfg = json_decode($addons['config'], true);
    }

    public function index()
    {
        $menu_list = $this->model->where(array('pid' => 0))->field(true)->select(); //顶级菜单
        foreach ($menu_list as $k => $v) {
            $menu_list[$k]['son'] = $this->model->where(array('pid' => $v['id']))->field(true)->select(); //子菜单
        }
        $this->assign('addons_menu_list', $menu_list);
        $this->assign('meta_title', '微信菜单管理');
        $this->display();
    }

    public function add()
    {
        if (IS_POST) {
            $count = $this->model->where(array('pid' => intval(I('post.pid'))))->count();
            if (!I('post.pid') && $count > 2) {
                $this->error('最多创建三个一级菜单');
            } elseif (I('post.pid') && $count > 4) {
                $this->error('最多创建五个子菜单');
            }
//            if(I('post.menu_type')=='view' && !strpos('http://',I('post.key'))){
//                $_POST['key']=U(I('post.key'),null,true,true);
//            }
            $result = $this->model->add(I('post.'));
            if ($result) {
                $this->success('添加菜单成功', addons_url('Weixin://Menu/index'));
            } else {
                $this->error('添加菜单失败');
            }
        } else {
            $menu_list = $this->model->where(array('pid' => 0))->field(true)->select(); //顶级菜单
            $this->assign('addons_menu_list', $menu_list);
            $this->assign('meta_title', '添加微信菜单');
            $this->display();
        }
    }

    public function edit()
    {
        $menu = $this->model->find(I('get.id'));
        if (IS_POST) {
            if ($menu['pid'] != I('post.pid')) {
                $count = $this->model->where(array('pid' => I('post.pid')))->count();
                if (!I('post.pid') && $count > 2) {
                    $this->error('最多创建三个一级菜单');
                } elseif (I('post.pid') && $count > 4) {
                    $this->error('最多创建五个子菜单');
                }
            }
            $result = $this->model->save(I('post.'));
            if ($result !== false) {
                $this->success('编辑菜单成功', addons_url('Weixin://Menu/index'));
            } else {
                $this->error('编辑菜单失败');
            }
        } else {
            $where['pid'] = 0;
            $where['id'] = array('neq', I('get.id'));
            $menu_list = $this->model->where($where)->field(true)->select(); //顶级菜单
            $this->assign('addons_menu_list', $menu_list);
            $this->assign('addons_menu_info', $menu);
            $this->assign('meta_title', '编辑微信菜单');
            $this->display('add');
        }
    }

    public function del()
    {
        $id = I('get.id');
        $result = $this->model->delete($id);
        if ($result) {
            $this->model->where(array('pid' => $id))->delete(); //删除对应菜单下的子菜单
            $this->success('删除菜单成功', addons_url('Weixin://Menu/index'));
        } else {
            $this->error('删除菜单失败');
        }
    }

    protected function display($name = '')
    {
        $name = $name ? $name : I('get._action');
        $tmpl = T('Addons://Weixin@Menu/' . $name);
        parent::display($tmpl);
    }

    //生成菜单
    public function build()
    {
        $data = $this->model->where(array('pid' => 0))->limit(0, 3)->select();

        foreach ($data as $v) {
            $button = array(
                'type' => $v['menu_type'],
                'name' => $v['name'],
            );
            switch ($button['type']) {
                case 'view':
                    $button['url'] = $v['key'];
                    break;
                case 'click':
                    $button['key'] = $v['key'];
                    break;
            }
            $sub_button = $this->model->where(array('pid' => $v['id']))->select();
            if (!empty($sub_button)) {
                foreach ($sub_button as $vv) {
                    $sub_menu = array(
                        'type' => $vv['menu_type'],
                        'name' => $vv['name'],
                    );
                    switch ($vv['menu_type']) {
                        case 'view':
                            $sub_menu['url'] = $vv['key'];
                            break;
                        case 'click':
                            $sub_menu['key'] = $vv['key'];
                            break;
                    }
                    $total_sub_menu[] = $sub_menu;
                }

                $button['sub_button'] = $total_sub_menu;
                unset($total_sub_menu);
            }
            $menu['button'][] = $button;
        }

        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $this->get_access_token();
        $res = $this->https_post($url, JSON($menu));
        $result = json_decode($res);
        if (!$result->errcode) {
            $this->success('微信菜单生成成功，请重新关注查看效果。');
        } else {
            $this->error('微信菜单生成失败，错误信息如下：' . $result->errmsg);
        }
    }

    /**
     * 获取微信ACCESS_TOKEN
     **/
    protected function get_access_token()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->cfg['appID'] . '&secret=' . $this->cfg['appsecret'];
        $tmp = json_decode($this->curlGet($url), true);
        $access_token = $tmp['access_token'];
        return $access_token;
    }

    /**
     * curl get 数据
     **/
    protected function curlGet($url)
    {
        $ch = curl_init();
        $header = array("Accept-Charset: utf-8");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        return curl_exec($ch);
    }

    /**
     * curl post 数据
     **/
    protected function https_post($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'Errno' . curl_error($curl);
        }
        curl_close($curl);
        return $result;
    }
}